package manager;

import analyser.IMibSyntaxAnalyzer;
import analyser.MibSyntaxAnalyzer;
import model.MibModule;
import model.MibNode;
import component.DaoComponent;
import dao.IMibModuleDao;
import dao.IMibNodeDao;
import util.common.FileUtils;

import java.util.LinkedList;
import java.util.List;

public class MibManager implements IMibManager {
    DaoComponent component;
    IMibModuleDao moduleDao;
    IMibNodeDao nodeDao;
    IMibSyntaxAnalyzer analyzer;

    public MibManager(DaoComponent component) {
        this(component, null);
    }

    public MibManager(DaoComponent component, IMibSyntaxAnalyzer analyzer) {
        this.initDaoComponent(component);
        this.initDefaultAnalyser(analyzer);
    }

    private void initDaoComponent(DaoComponent component){
        if (null == component){
            throw new IllegalArgumentException();
        }
        this.component = component;
        moduleDao = component.moduleDao;
        nodeDao = component.nodeDao;
    }

    private void initDefaultAnalyser(IMibSyntaxAnalyzer analyzer){
        if (null == analyzer){
            analyzer = new MibSyntaxAnalyzer(this);
        }
        this.analyzer = analyzer;
    }

    @Override
    public void installMibFile(String mibFilePath) {

    }

    @Override
    public void installMibByText(String text) {
    }

    /**
     * 解析MIB文件
     * @param mibFilePath
     * @return
     */
    @Override
    public MibModule analysisMibFile(String mibFilePath) {
        String txt = FileUtils.readAllText(mibFilePath);
        return analysisMibText(txt);
    }

    /**
     * 解析MIB文本
     * @param mibText
     * @return
     */
    @Override
    public MibModule analysisMibText(String mibText) {
        IMibSyntaxAnalyzer analyzer = new MibSyntaxAnalyzer(this);
        MibModule module = null;
        try{
            module = analyzer.analyse(mibText);
        }catch (Exception e){
            e.printStackTrace();
        }
        return module;
    }

    /**
     * 根据模块名获取节点
     * @param moduleName
     * @return
     */
    @Override
    public List<MibNode> getNodeListByName(String moduleName) {
        try {
            List<MibNode> nodeList = nodeDao.getByModuleName(moduleName);
            if (nodeList == null)
                nodeList = new LinkedList<>();
            return nodeList;
        }catch (Exception e){
            e.printStackTrace();
            return new LinkedList<>();
        }
    }

    /**
     * 判断模块是否存在
     * @param moduleName
     * @return
     */
    @Override
    public boolean isModuleExist(String moduleName) {
        return moduleDao.isModuleExist(moduleName);
    }
}
